# make a directory, or exit if failed
mkdir_wrapper() {
  dir=$1
  good_arg $dir dir

  mkdir -p $dir;
  if [[ ! -d $dir ]];
    then
      echo "error, no dir: $dir"
      exit
  fi
}

good_arg() {
  if [[ ! $# == 2 ]];
    then 
    echo "bad number of args in good_arg: $#"
    exit
  fi
  arg=$1
  argname=$2
  [[ -z "$1" ]] && exit "bad arg, seems to be blank. argname: $argname"
}

exit_wrapper() {
  msg=$1
  echo "exiting, msg: $msg"
  exit
}

install_hard_cpan_mod() {
  mod=$1
  install_command=$2
  backup_prefix=$3
  if [ ! -n "$backup_prefix" ]; 
  then
    echo "error: no backup prefix"
    exit
  fi

  perl -M$mod -e ''
  if [ ! $? -eq 0 ]; # if the last command resulted in an error, eg module not found
    then 
      echo $mod not installed under `which perl`
      echo attempting to install $mod
      $install_command
      perl -M$mod -e ''
      if [ ! $? -eq 0 ];
	then 
	  echo "error: unable to install $mod with `which perl`"
	  exit
      else
	echo "successfully installed `perldoc -l $mod`"
	backup_external_deps ${backup_prefix}_installed
      fi
  else 
    echo "$mod installed at `perldoc -l $mod`"
    echo "skipping $mod install"
  fi
}

pmc_svn_checkout() {
  topdir=$1
  checkoutdir=$2
  repo=$3
  backup_prefix=$4
  if [ ! -n "$backup_prefix" ]; 
  then
    echo "error: no backup prefix"
    exit
  fi

  mkdir_wrapper $topdir
  if [[ ! -d $checkoutdir ]];
    then
    echo "repo not checked out at $checkoutdir"
    echo "checking it out now....."
    pushd $topdir 
      echo svn co $repo
      svn co $repo
    popd
    backup_external_deps $backup_prefix
  else
    echo "$repo checked out in in $checkoutdir"
    echo "Skipping svn checkout"
  fi

}

backup_external_deps() {
  note=$1 #optional
  nowtime=`date +%Y-%m-%d-%H%M`
  mkdir -p $BACKUPS
  tarfile=$BACKUPS/external_dependencies_current-$note-$nowtime.tar.gz
  echo backing up $EXTERNAL_DEPENDENCIES_TOP/current into $tarfile
  tar -C $EXTERNAL_DEPENDENCIES_TOP -czvf $tarfile current > /dev/null
}

revert_external_deps() {
  tarfile=$1
  [ -n $tarfile ] || exit_wrapper "no tarfile"
  [ -f $tarfile ] || exit_wrapper "not a file: $tarfile"
  rm -rf $EXTERNAL_DEPENDENCIES
  echo restoring current external dependencies dir from $tarfile
  tar -C $EXTERNAL_DEPENDENCIES_TOP -xzvf $tarfile > /dev/null
}



